package com.gonsin.gview.example.config;

import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {

    @Autowired
    private OpenApiExtensionResolver openApiExtensionResolver;

    @Bean
    public Docket webApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                //指定提供接口所在的基包
                .apiInfo(apiInfo("GView接口","", "1.0"))
                .groupName("GView接口")
                .globalOperationParameters(getGlobalOperationParameters())
                .select()
                .apis(input -> input.isAnnotatedWith(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .extensions(openApiExtensionResolver.buildExtensions("GView接口"));
    }


    private ApiInfo apiInfo(String name, String description, String version) {
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title(name)
                .license("")
                .description(description)
                .version(version).build();
        return apiInfo;
    }

    private List<Parameter> getGlobalOperationParameters() {
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        parameterBuilder
                .name("sessionId")
                .description("会话id")
                .defaultValue(RandomStringUtils.random(32, true, true))
                .modelRef(new ModelRef("string"))
                .parameterType("query")
                .required(true);
        pars.add(parameterBuilder.build());
        return pars;
    }

}
